<?php

/**
 * 华为小号功能
 * 把真实号码绑定一个虚拟号， 拨打的时候拨打虚拟号
 */
class HuaweiAx
{
    protected $config;
    
    public function __construct($config)
    {
        $this->config = $config;
    }
    
    /**
     * 绑定 A - x 的对应关系，  呼叫 X， 则 x 会呼叫 A
     * @param  $telA string 用户真实号码
     * @return mixed
     * @throws \Exception
     */
    public function bind($telA)
    {
        $param = [
            'requestId' => uniqid(),
            'telA' => (string)$telA,
            'areacode' => '10',
            'subts' => (string)date('YmdHis'),
            'expiration' => $this->config['expiration'],
            'extra' => ['callrecording' => '1', 'callpickup' => '1'],
        ];
        
        $header = $this->createHeader();
        
        $header['msgdgt'] = $this->createSign($header, $param);
        
        $rawResult = HttpClient::postJson($this->config['host'], $this->config['uri'], $param, $header);
        $result = json_decode($rawResult, true);
        
        if ($result['code'] != 0) {
            throw new \Exception($result['message']);
        }
        return $result;
    }
    
    private function createHeader()
    {
        return [
            'appkey' => $this->config['appkey'],
            'ts' => date('YmdHis') . '000',
        ];
    }
    
    private function createSign($header, $body)
    {
        $data = array_merge($header, $body);
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $_k => $_v) {
                    $data[$_k] = $_v;
                }
                unset($data[$k]);
            }
        }
        
        ksort($data);
        $str = $this->config['appsecret'];
        foreach ($data as $k => $v) {
            $str .= $k . $v;
        }
        return strtoupper(md5($str));
    }
}
